//
//  PxHomeViewController.m
//  OilCard
//
//  Created by Xu Yefeng on 14-5-18.
//  Copyright (c) 2014年 Free. All rights reserved.
//

#import "PxWayBillSaveViewController.h"
#import "PxFormValidate.h"

@implementation PxWayBillSaveViewController {
    BOOL isContinues;
    NSArray *compArray;
    NSString *companyCode;
    NSString *expressCompany;
}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        isContinues = NO;
        compArray = [PxGlobal getData:COMPANY_INFO];
        if (compArray.count > 0) {
            companyCode = compArray[0][@"value"];
            expressCompany = compArray[0][@"label"];
        } else {
            companyCode = @"error";
            expressCompany = @"error";
        }
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    CGFloat width = self.view.width;
    NSString *packageNum = [PxGlobal getData:PACKAGE_NUM];
    PxTextField *textfield = [PxWidgetCreater getTextField:@"请输入集包号..."];
    textfield.frame = CGRectMake(0, 15, width, [PxGlobal getCustomerHeight:45]);
    [self.view addSubview:textfield];
    if (packageNum && packageNum.length >0)
        textfield.text = packageNum;
    self.packageTextField = textfield;
    
    PxTextField *textfield2 = [PxWidgetCreater getTextField:@"请输入手机号..."];
    textfield2.frame = CGRectMake(0, textfield.bottom + 15, width, [PxGlobal getCustomerHeight:45]);
    textfield2.keyboardType = UIKeyboardTypePhonePad;
    [self.view addSubview:textfield2];
    self.telTextField = textfield2;
    
    PxTextField *textfield3 = [PxWidgetCreater getTextField:@"请输入代收运费..."];
    textfield3.frame = CGRectMake(0, textfield2.bottom + 15, width, [PxGlobal getCustomerHeight:45]);
    textfield3.keyboardType = UIKeyboardTypePhonePad;
    [self.view addSubview:textfield3];
    self.freightTextField = textfield3;
    
    PxTextField *textfield4 = [PxWidgetCreater getTextField:@"请输入代收货款..."];
    textfield4.frame = CGRectMake(0, textfield3.bottom + 15, width, [PxGlobal getCustomerHeight:45]);
    textfield4.keyboardType = UIKeyboardTypePhonePad;
    [self.view addSubview:textfield4];
    self.paymentTextField = textfield4;
    
    UIButton *btn = [[UIButton alloc] initWithFrame:CGRectMake(15, textfield4.bottom + 20, width-15*2, [PxGlobal getCustomerHeight:40])];
    btn.layer.cornerRadius = 3;
    btn.layer.masksToBounds = YES;
    btn.backgroundColor = [UIColor colorWithHTMLStr:@"ff4e08"];
    [btn setTitle:@"确定"];
    btn.titleLabel.font = [UIFont systemFontOfSize:18];
    btn.titleLabel.textColor = [UIColor colorWithHTMLStr:@"ffffff"];
    [self.view addSubview:btn];
    [btn setSelector:@selector(save) withTarget:self];
    
    [self setRightBtn:@"选择"];
}

-(void)setRightBtn:(NSString *)title
{
    UIButton *navBarRightButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 30, 44)];
    [navBarRightButton addTarget:self action:@selector(navBarRightBtnAction) forControlEvents:UIControlEventTouchUpInside];
    [navBarRightButton setContentMode:UIViewContentModeCenter];
    
    [navBarRightButton setTitle:title];
    
    navBarRightButton.titleLabel.font = [UIFont systemFontOfSize:15];
    UIColor *color1 = [UIColor colorWithHTMLStr:@"ff4e08"];
    [navBarRightButton setTitleColor:color1 forState:UIControlStateNormal];
    
    UIBarButtonItem *rightButtonItem=[[UIBarButtonItem alloc] initWithCustomView:navBarRightButton];
    
    UIBarButtonItem *negativeSpacer = [[UIBarButtonItem alloc]
                                       initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace
                                       target:nil action:nil];
    if([LLYTSmallUtil iOSBigVersion] >= 6.5)
        negativeSpacer.width = -9;// it was -6 in iOS 6
    else
        negativeSpacer.width = 1;
    
    [self.navigationItem setRightBarButtonItems:[NSArray arrayWithObjects:negativeSpacer,rightButtonItem/*this will be the button which u actually need*/, nil] animated:NO];
}

- (void)navBarRightBtnAction
{
    NSMutableArray *arr = [NSMutableArray new];
    for (NSDictionary *data in compArray) {
        [arr addObject:data[@"label"]];
    }
    if (!_pickViewController) {
        _pickViewController = [[PxAlertPickViewController alloc] initWithDataSource:arr];
        _pickViewController.delegate = self;
        _pickViewController.modalPresentationStyle = UIModalPresentationOverCurrentContext;
        _pickViewController.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
        _pickViewController.view.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0.6];
    }
    [self presentViewController:_pickViewController animated:YES completion:nil];
}

- (void)buttonClick:(NSInteger)row
{
    NSDictionary *data = compArray[row];
    companyCode = data[@"value"];
    expressCompany = data[@"label"];
    [self setRightBtn:expressCompany];
    [self setLogoTitleView];
    // 保存选中的值，方便下次设置默认值
    [PxGlobal saveData:companyCode andKey:COMPANY_CODE];
    [PxGlobal saveData:expressCompany andKey:COMPANY_NAME];
}

- (UIView*)setLogoTitleView
{
    UIView *titleView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 160, 44)];
    titleView.backgroundColor = [UIColor clearColor];
    
    UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 160, 30)];
    titleLabel.font = [UIFont systemFontOfSize:18.f];
    titleLabel.textColor = [UIColor blackColor];
    titleLabel.backgroundColor = [UIColor clearColor];
    titleLabel.textAlignment = NSTextAlignmentCenter;
    titleLabel.text = expressCompany;
    [titleView addSubview:titleLabel];
    
    UILabel *subTitle = [[UILabel alloc] initWithFrame:CGRectMake(0, 25, 160, 14)];
    subTitle.font = [UIFont systemFontOfSize:12.f];
    subTitle.textColor = [UIColor blackColor];
    subTitle.backgroundColor = [UIColor clearColor];
    subTitle.textAlignment = NSTextAlignmentCenter;
    subTitle.text = self.incomingParam[@"waybillNo"];
    [titleView addSubview:subTitle];
    
    self.navigationItem.titleView = titleView;
    
    return titleView;
}

-(BOOL)checkData
{
//    if ([self isEmpty:self.view.subviews])
//        return NO;
    if (companyCode.length <= 0) {
        [self showMSG:@"快递公司不能为空" withType:1];
        return NO;
    }
    NSString *phone = self.telTextField.text;
    BOOL isOk = [[PxFormValidate sharedInstance] checkPhone:phone];
    if (!isOk) {
        //TODO:
        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"提示" message:[NSString stringWithFormat:@"手机号不符合现有规则，是否继续"] preferredStyle: UIAlertControllerStyleAlert];
        UIAlertAction *OKAction = [UIAlertAction actionWithTitle:@"是" style:UIAlertActionStyleDestructive handler:^(UIAlertAction *action){
            isContinues = YES;
            [self save];
        }];
        UIAlertAction *CancelAction = [UIAlertAction actionWithTitle:@"否" style:UIAlertActionStyleDestructive handler:nil];
        [alertController addAction:OKAction];
        [alertController addAction:CancelAction];
        [self presentViewController:alertController animated:YES completion:nil];
        return NO;
    }
    return YES;
}

-(void)save
{
    if (!isContinues) {
        BOOL isOk = [self checkData];
        if (!isOk)
            return;
    }
    [self infoUpload];
}

-(void)saveInLocal
{
    NSDate *senddate=[NSDate date];
    NSDateFormatter *dateformatter=[[NSDateFormatter alloc] init];
    [dateformatter setDateFormat:@"MM-dd hh:mm"];
    NSString *locationString=[dateformatter stringFromDate:senddate];
    
    int success = [PxGlobal insertOrUpdateTable:TABLE_APARTMENT withData:@{
                                                                            @"waybillNo":[PxGlobal getDicValue:@"waybillNo" fromDic:self.incomingParam],
                                                                            @"expressCompany":companyCode,
                                                                            @"areaCode":self.packageTextField.text,
                                                                            @"phone":self.telTextField.text,
                                                                            @"payFreight":self.freightTextField.text,
                                                                            @"payment":self.paymentTextField.text,
                                                                            @"sendTime":locationString
                                                                            }];
    if (success != -1)
        [self popToLastControllerWithIncomingParam:@{@"type":@"1",
                                                     @"title":@"扫描分区"}];
    else {
        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"提示" message:[NSString stringWithFormat:@"添加失败，请重新操作"] preferredStyle: UIAlertControllerStyleAlert];
        UIAlertAction *OKAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDestructive handler:nil];
        [alertController addAction:OKAction];
        [self presentViewController:alertController animated:YES completion:nil];
    }
}

-(void)infoUpload
{
    [PxGlobal saveData:self.packageTextField.text andKey:PACKAGE_NUM];
    NSDate *senddate=[NSDate date];
    NSDateFormatter *dateformatter=[[NSDateFormatter alloc] init];
    [dateformatter setDateFormat:@"MM-dd hh:mm"];
    NSString *locationString=[dateformatter stringFromDate:senddate];
    
    PxBaseOilNetCmd *cmd = [PxBaseOilNetCmd cmd];
    cmd.functionName = TRANS_WAYBILL_INFO_UPLOAD;
    
    [cmd.paramDic addEntriesFromDictionary:@{@"waybills":@[
                                                     @{@"waybillNo":[PxGlobal getDicValue:@"waybillNo" fromDic:self.incomingParam],
                                                           @"expressCompany":companyCode,
                                                           @"areaNum":self.packageTextField.text,
                                                           @"receiverPhone":self.telTextField.text,
                                                           @"payFreight":self.freightTextField.text,
                                                           @"payment":self.freightTextField.text,
                                                           @"sendTime":locationString}
                                                     ]}];
    
    cmd.businessSuccessHandler = ^(NSDictionary* dic)
    {
        NSString *msg = dic[@"resultDesc"];
        if (!msg || msg < 0)
            msg = @"上传成功";
            
        [LLAlertService alertWithTip:msg];
        [self popToLastControllerWithIncomingParam:@{@"type":@"1",
                                                     @"title":@"扫描分区"}];
    };
    
    cmd.businessErrorHandler = ^(NSDictionary* dic)
    {
        [LLAlertService sysAlertWithTip:dic[RESULT_DESC] withTitle:@"错误"];
    };
    
    cmd.errorHandler = ^(NSError* error)
    {
        
    };
    
    
    [LLRestEngine sendCommandRequest:cmd];
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
}

- (void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    if (self.incomingParam) {
        companyCode = self.incomingParam[@"companyCode"];
        expressCompany = self.incomingParam[@"expressCompany"];
        [self setLogoTitleView];
    }
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
